<?php
namespace app\admin\controller;
use app\admin\model\{Order as OrderModel,StoreOrderStatus,OrderCartInfo,UserMerchant};
use think\facade\Db;
use app\common\BaseController;

class Order extends  BaseController{

	/**
	 * 订单列表
	 * @return [type] [description]
	 */
	public  function index(){
        $page  = (int)request()->param('page', 0);
        $limit  = (int)request()->param('limit', 10);
        $search = request()->param();
        $wheres = [];
        $query  = OrderModel::search_model($search)->append(['status_text']);
        
        $total  = $query->count();
        $data   = $query->page($page, $limit)->order('id desc')->select();
        $count_data = [];
        $count_data['all']    = OrderModel::count(); //全部订单
        $count_data['count0'] = OrderModel::where('paid', 0)->where('status', 0)->count();//未支付
        $count_data['count1'] = OrderModel::where('paid', 1)->where('status', 1)->count();// 待发货
        $count_data['count2'] = OrderModel::where('paid', 1)->where('status', 2)->count();//待收货
        $count_data['count3'] = OrderModel::where('paid', 1)->where('status', 3)->where('refund_status', 0)->count();//已收货
        $count_data['count4'] = OrderModel::where('paid', 1)->where('status', 4)->count(); //申请退款
        $count_data['count5'] = OrderModel::where('paid', 1)->where('status', 5)->count(); //申请退款通过
        $count_data['count6'] = OrderModel::where('paid', 1)->where('status', 6)->count(); //申请退款拒绝
        $count_data['count7'] = OrderModel::where('paid', 1)->where('status', 7)->count(); //已评价
        $merchant_list  = UserMerchant::where('is_del',0)->select();
        return $this->success('', [
            'start' => $page,
            'limit' => $limit,
            'data'  => $data,
            'total' => $total,
            'count_data' => $count_data,
            'merchant_list' => $merchant_list
        ]);
    }

    /**
     * 导出
     * @return void
     * @author Sam
     * @date 2022-05-09
     */
    public function export(){
        $search = request()->param();
        $wheres = [];
        $query  = OrderModel::search_model($search)->append(['status_text']);
        $total  = $query->count();
        $data   = $query->order('id desc');
        \big_array_to_csv($data,'订单导出',[
            'order_id' => '订单号',
            'real_name' => '收货人姓名',
            'user_phone' => '收货人电话',
            'user_address' => '收货地址',
            'goods_name'  => ['商品信息',function($item){
            $_info = OrderCartInfo::where('oid', $item['id'])->column('cart_info');
            $goodsName = [];
            $cart_sum = 0;
            foreach ($_info as $k => $v) {
                $v = json_decode($v, true);
                $suk = '';
                if (isset($v['productInfo']['attrInfo'])) {
                    if (isset($v['productInfo']['attrInfo']['suk'])) {
                        $suk = '(' . $v['productInfo']['attrInfo']['suk'] . ')';
                    }
                }
                $goodsName[] = implode(
                    [$v['productInfo']['store_name'],
                        $suk,
                        "[{$v['cart_num']} * {$v['truePrice']}]"
                    ], ' ');
                $cart_sum += $v['cart_num'];
            }
            return implode(',',$goodsName) ;
            }],
            'cart_sum' => ['商品总数',function($item){
                $_info = OrderCartInfo::where('oid', $item['id'])->column('cart_info');
                $cart_sum = 0;
                foreach ($_info as $k => $v) {
                    $v = json_decode($v, true);
                    $cart_sum += $v['cart_num'];
                }
                return $cart_sum;
            }],
            'total_price' => '订单总金额',
            'pay_price' => '实际支付金额',
            'coupon_price' => '优惠金额',
            'paid' =>  ['是否支付',function($item){
                return $item['paid'] == 1 ? '是' : '否';
            }],
            'pay_time' => ['支付时间',function($item){
                return $item['pay_time'] ? date('Y-m-d H:i:s',$item['pay_time']) : '';
            }],
            'status_text' => '订单状态',
            'add_time' => '下单时间',
            'remark' => '用户订单备注',
        ]);
    }

    /**
     * 订单详情
     * @return [type] [description]
     */
    public function detail(int $id){
        try {
            $row  = OrderModel::with(['cart_detail','user','coupon'])->where('id', $id)->append(['status_text'])->find();
        } catch (DataNotFoundException | ModelNotFoundException | DbException $e) {
            return $this->error($e->getMessage());
        }
        return $this->success('', $row);
    }

    /**
     * 订单日志记录
     * @return [type] [description]
     */
    public function order_log(int $id){
        $page  = (int)request()->param('page', 0);
        $limit  = (int)request()->param('limit', 10);
        $search = request()->param();
        $wheres = [];
        $query  = StoreOrderStatus::where('oid',$id);
        $total  = $query->count();
        $data   = $query->page($page, $limit)->order('change_time desc')->select();
        return $this->success('', [
            'start' => $page,
            'limit' => $limit,
            'data'  => $data,
            'total' => $total,
        ]);
    }

    /**
     * 修改订单
     * @return [type] [description]
     */
    public function edit(){
        $id = \param_check('id');
        if(request()->isPost()) {
            $data = request()->post();
            try{
                OrderModel::update($data,['id'=>$id]);
                StoreOrderStatus::setStatus($id, 'order_edit', '修改商品总价为：' . $data['total_price'] . ' 实际支付金额' . $data['pay_price'].'收货地址为'.$data['user_address']);
                Db::commit();
            }catch(\Exception $e){
                Db::rollback();
                json_response(0,$e->getMessage());  
            }
            json_response(1,'操作成功');  
         
         }else{
            $data   = OrderModel::find($id);
            $option = [
                ['title'=>'顺丰快递','value'=>'SF'],
                ['title'=>'中通快递','value'=>'ZTO'],
                ['title'=>'EMS','value'=>'EMS'],
                ['title'=>'中国邮政','value'=>'YZ'],
                ['title'=>'圆通快递','value'=>'YT']
            ];
            return $this->render_form([
                ['type'=>'text', 'name'=>'order_id', 'title'=>'订单号', 'lay-verify'=>'required','disabled'=>true],
                ['type'=>'text','text_type'=>'number' ,'name'=>'total_price', 'title'=>'订单总价'],
                ['type'=>'text', 'text_type'=>'number','name'=>'pay_price', 'title'=>'支付价格'],
                ['type'=>'text', 'name'=>'user_address', 'title'=>'收货地址']
            ],$data);
         }
    }
    /**
     * 物流信息
     * @return [type] [description]
     */
    public function distribution(){
        $id = \param_check('id');
        if(request()->isPost()) {
            $data = request()->post();
            try{
                OrderModel::update($data,['id'=>$id]);
                StoreOrderStatus::setStatus($id, 'distribution', '修改发货信息为' . $data['delivery_name'] . '号' . $data['delivery_id'],$this->mg_user['username']);
                Db::commit();
            }catch(\Exception $e){
                Db::rollback();
                json_response(0,$e->getMessage());  
            }
            json_response(1,'操作成功');  
         
         }
    }

    /**
     * 发货
     * @return [type] [description]
     */
    public function deliver(){
        $id = \param_check('id');
            $data = request()->post();
            try{
                $data['status'] = 2;
                $data['deliver_time'] = date('Y-m-d H:i:s');
                OrderModel::update($data,['id'=>$id]);
                StoreOrderStatus::setStatus($id, 'delivery_goods', '已发货 快递公司：' . $data['delivery_name'] . ' 快递单号：' . $data['delivery_id']);
                Db::commit();
            }catch(\Exception $e){
                Db::rollback();
                json_response(0,$e->getMessage());  
            }
            json_response(1,'操作成功');  
    
    }

    /**
     * 退款审核通过
     * @return [type] [description]
     */
    public function  refund_y(){
        $id = \param_check('id');
            $data = request()->post();
            try{
                $product = OrderModel::find($id);
                if (!$product) exception('数据不存在!');
                if (!$data['refund_price']) exception('请输入退款金额');
                if($product->refund_status !=1) exception('订单状态异常');
                $bj = bccomp((float)$product['pay_price'], (float)$data['refund_price'], 2);
                if ($bj < 0) exception('退款金额大于支付金额，请修改退款金额');
                $data['status'] = 5;
                $service = new \app\common\api\WeChat;
                $refund_order_sn = 'TK'.time(); //退款单号  自行生成
                $res = $service->doRefund($product->pay_price,$data['refund_price'],$refund_order_sn,$product->transaction_id);
                $data['refund_sn']   = $refund_order_sn;
                OrderModel::update($data,['id'=>$id]);
                StoreOrderStatus::setStatus($id, 'refund_price', '退款给用户' . $data['refund_price'] . '元');
                Db::commit();
            }catch(\Exception $e){
                Db::rollback();
                json_response(0,$e->getMessage());  
            }
            json_response(1,'操作成功');  

    }
	
    /**
     * 退款拒绝
     * @return [type] [description]
     */
    public function  refund_n(){
        $id = \param_check('id');
            $data = request()->post();
            try{
                $product = OrderModel::find($id);
                if (!$product) exception('数据不存在!');
               if (!$data['refund_reason']) exception('请输入退款原因');
                $data['status'] = 6;
                OrderModel::update($data,['id'=>$id]);
                StoreOrderStatus::setStatus($id, 'refund_n', '不退款原因:' . $data['refund_reason']);
                Db::commit();
            }catch(\Exception $e){
                Db::rollback();
                json_response(0,$e->getMessage());  
            }
            json_response(1,'操作成功'); 
    }
}